import pygame
import random
import math

# 初始化Pygame
pygame.init()

# 设置窗口
WIDTH = 800
HEIGHT = 600
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("精致太空射击游戏")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
GRAY = (100, 100, 100)

# 加载音效（可选，需要准备文件）
try:
    shoot_sound = pygame.mixer.Sound("shoot.wav")  # 需要一个射击音效文件
    explosion_sound = pygame.mixer.Sound("explosion.wav")  # 需要一个爆炸音效文件
except:
    shoot_sound = None
    explosion_sound = None

# 玩家飞船
player_size = 40
player_x = WIDTH // 2
player_y = HEIGHT - 60
player_speed = 6

# 子弹
bullet_radius = 5
bullet_speed = -12
bullets = []

# 敌人
enemy_size = 30
enemy_speed = 4
enemies = []

# 爆炸效果
explosions = []

# 背景星星
stars = [(random.randint(0, WIDTH), random.randint(0, HEIGHT)) for _ in range(50)]

# 分数
score = 0
font = pygame.font.Font(None, 36)

# 游戏循环
clock = pygame.time.Clock()
running = True

def draw_ship(x, y):
    points = [(x, y - player_size // 2), (x - player_size // 2, y + player_size // 2),
              (x + player_size // 2, y + player_size // 2)]
    pygame.draw.polygon(window, WHITE, points)
    pygame.draw.polygon(window, GRAY, points, 2)

def spawn_enemy():
    x = random.randint(enemy_size, WIDTH - enemy_size)
    enemies.append([x, -enemy_size, random.uniform(2, enemy_speed)])

def draw_explosion(x, y, frame):
    if frame < 10:
        radius = frame * 3
        pygame.draw.circle(window, YELLOW, (int(x), int(y)), radius, 2)
        pygame.draw.circle(window, RED, (int(x), int(y)), radius // 2)

# 初始敌人
spawn_enemy()

while running:
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                bullets.append([player_x, player_y - player_size // 2])
                if shoot_sound:
                    shoot_sound.play()

    # 玩家移动
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player_x > player_size // 2:
        player_x -= player_speed
    if keys[pygame.K_RIGHT] and player_x < WIDTH - player_size // 2:
        player_x += player_speed

    # 子弹移动
    for bullet in bullets[:]:
        bullet[1] += bullet_speed
        if bullet[1] < 0:
            bullets.remove(bullet)

    # 敌人移动
    for enemy in enemies[:]:
        enemy[1] += enemy[2]
        if enemy[1] > HEIGHT:
            enemies.remove(enemy)
            spawn_enemy()

    # 碰撞检测
    player_rect = pygame.Rect(player_x - player_size // 2, player_y - player_size // 2, 
                            player_size, player_size)
    for enemy in enemies[:]:
        enemy_rect = pygame.Rect(enemy[0] - enemy_size // 2, enemy[1] - enemy_size // 2, 
                                enemy_size, enemy_size)
        if player_rect.colliderect(enemy_rect):
            running = False
        for bullet in bullets[:]:
            if math.hypot(bullet[0] - enemy[0], bullet[1] - enemy[1]) < enemy_size // 2 + bullet_radius:
                bullets.remove(bullet)
                explosions.append([enemy[0], enemy[1], 0])
                enemies.remove(enemy)
                score += 10
                spawn_enemy()
                if explosion_sound:
                    explosion_sound.play()
                break

    # 随机生成敌人
    if random.random() < 0.03:
        spawn_enemy()

    # 更新爆炸效果
    for explosion in explosions[:]:
        explosion[2] += 1
        if explosion[2] >= 10:
            explosions.remove(explosion)

    # 绘制背景
    window.fill(BLACK)
    for star in stars:
        pygame.draw.circle(window, WHITE, star, 1)

    # 绘制飞船、子弹、敌人
    draw_ship(player_x, player_y)
    for bullet in bullets:
        pygame.draw.circle(window, YELLOW, (int(bullet[0]), int(bullet[1])), bullet_radius)
    for enemy in enemies:
        pygame.draw.circle(window, RED, (int(enemy[0]), int(enemy[1])), enemy_size // 2)
        pygame.draw.circle(window, GRAY, (int(enemy[0]), int(enemy[1])), enemy_size // 4)

    # 绘制爆炸
    for explosion in explosions:
        draw_explosion(explosion[0], explosion[1], explosion[2])

    # 显示分数
    score_text = font.render(f"Score: {score}", True, WHITE)
    window.blit(score_text, (10, 10))

    # 更新显示
    pygame.display.flip()
    clock.tick(60)

# 游戏结束
print(f"游戏结束！你的分数是: {score}")
pygame.quit()